package cn.micro.eye.commons.configuration;

import cn.micro.eye.commons.auth.AuthContext;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Nullable;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Micro Spring Configuration
 *
 * @author lry
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(MicroProperties.class)
public class MicroSpringConfiguration implements BeanFactoryAware, WebMvcConfigurer, InitializingBean {

    public static List<String> packages = new ArrayList<>();

    @Resource
    private MicroProperties properties;

    @Override
    public void setBeanFactory(@Nullable BeanFactory beanFactory) throws BeansException {
        if (beanFactory == null) {
            return;
        }

        List<String> tempPackages = AutoConfigurationPackages.get(beanFactory);
        if (tempPackages == null || tempPackages.isEmpty()) {
            return;
        }
        packages.addAll(tempPackages);
    }

    @Override
    public void afterPropertiesSet() {
        AuthContext.initialize(properties.getTokenExpiresSec(), properties.getRefreshTokenSec());
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        converters.add(fastConverter);
    }

}
